import React, { useState, useEffect } from 'react';
import { Table, Form, Input, DatePicker, Button, Space, Card, Tooltip } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import axios from 'axios';
import moment from 'moment';
import 'antd/dist/reset.css';
import './App.css';
import Login from './components/Login';

const { RangePicker } = DatePicker;

function App() {
  const [form] = Form.useForm();
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);
  const [dateRange, setDateRange] = useState([]);
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  useEffect(() => {
    const loginStatus = localStorage.getItem('isLoggedIn');
    if (loginStatus === 'true') {
      setIsLoggedIn(true);
    }
  }, []);

  const handleLogin = () => {
    setIsLoggedIn(true);
  };

  const handleLogout = () => {
    localStorage.removeItem('isLoggedIn');
    setIsLoggedIn(false);
  };

  const handleUsernameClick = (username) => {
    form.setFieldsValue({ username });
    fetchData({ current: 1, username, latest_only: false });
  };

  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 50,
    },
    {
      title: '用户ID',
      dataIndex: 'username',
      key: 'username',
      width: 130,
      align: 'left',
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          <Button 
            type="link" 
            onClick={() => handleUsernameClick(text)}
            style={{ 
              whiteSpace: 'normal', 
              height: 'auto',
              padding: '4px 0',
              margin: 0,
              lineHeight: '1.5',
              width: '100%',
              textAlign: 'left',
              overflow: 'hidden',
              textOverflow: 'ellipsis',
              display: 'block'
            }}
          >
            {text}
          </Button>
        </Tooltip>
      ),
    },
    {
      title: '问题',
      dataIndex: 'text',
      key: 'text',
      width: 130,
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '知识库内容',
      dataIndex: 'context',
      key: 'context',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '回答',
      dataIndex: 'answer',
      key: 'answer',
      width: 200,
      ellipsis: {
        showTitle: false,
      },
      render: (text) => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '网络IP',
      dataIndex: 'ip',
      key: 'ip',
      width: 90,
    },
    {
      title: '创建时间',
      dataIndex: 'create_time',
      key: 'create_time',
      width: 120,
      render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss'),
    },
  ];

  const fetchData = async (params = {}) => {
    setLoading(true);
    try {
      const { current, pageSize, username: paramUsername, latest_only = true } = params;
      const { username: formUsername } = form.getFieldsValue();
      const finalUsername = paramUsername !== undefined ? paramUsername : formUsername;
      
      let queryParams = new URLSearchParams({
        page: current || 1,
        page_size: pageSize || 10,
        latest_only: String(latest_only),
      });

      if (finalUsername) {
        queryParams.append('username', finalUsername);
      }

      if (dateRange?.[0]) {
        const startDate = dateRange[0].format('YYYY-MM-DDTHH:mm:ss');
        queryParams.append('start_date', startDate);
      }

      if (dateRange?.[1]) {
        const endDate = dateRange[1].format('YYYY-MM-DDTHH:mm:ss');
        queryParams.append('end_date', endDate);
      }

      const response = await axios.get(`/api/search-records?${queryParams}`);
      
      setData(response.data.items);
      setPagination({
        current: response.data.page,
        pageSize: response.data.page_size,
        total: response.data.total,
      });
    } catch (error) {
      console.error('Failed to fetch data:', error);
    } finally {
      setLoading(false);
    }
  };

  const handleTableChange = (newPagination) => {
    fetchData({
      current: newPagination.current,
      pageSize: newPagination.pageSize,
      latest_only: !form.getFieldValue('username'),
    });
  };

  const handleSearch = () => {
    const username = form.getFieldValue('username');
    fetchData({ 
      current: 1,
      latest_only: !username 
    });
  };

  const handleReset = () => {
    form.resetFields();
    setDateRange([]);
    fetchData({ 
      current: 1,
      latest_only: true 
    });
  };

  const handleDateRangeChange = (dates) => {
    setDateRange(dates);
  };

  useEffect(() => {
    if (isLoggedIn) {
      fetchData({ latest_only: true });
    }
  }, [isLoggedIn]);

  if (!isLoggedIn) {
    return <Login onLogin={handleLogin} />;
  }

  return (
    <div className="app-container" style={{ padding: '24px' }}>
      <Card 
        title="搜索记录查询"
        extra={
          <Button type="link" onClick={handleLogout}>
            退出登录
          </Button>
        }
      >
        <Form
          form={form}
          layout="inline"
          style={{ marginBottom: '24px' }}
        >
          <Form.Item name="username">
            <Input
              placeholder="请输入用户ID"
              prefix={<SearchOutlined />}
              allowClear
            />
          </Form.Item>
          <Form.Item>
            <RangePicker
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              value={dateRange}
              onChange={handleDateRangeChange}
            />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" onClick={handleSearch}>
                搜索
              </Button>
              <Button onClick={handleReset}>
                重置
              </Button>
            </Space>
          </Form.Item>
        </Form>

        <Table
          columns={columns}
          dataSource={data}
          rowKey={(record) => record.id}
          pagination={pagination}
          loading={loading}
          onChange={handleTableChange}
          scroll={{ x: 1300 }}
          size="middle"
        />
      </Card>
    </div>
  );
}

export default App;
